package com.sdry.web.controller.base;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.sdry.base.BaseController;
import com.sdry.entity.base.Department;
import com.sdry.entity.base.Job;
import com.sdry.entity.base.Staff;
import com.sdry.service.base.DepartmentService;
import com.sdry.service.base.JobService;
import com.sdry.service.base.RegService;
import com.sdry.service.base.StaffService;
import com.sdry.utils.CreateFileReturnPath;
import com.sdry.utils.DateJsonValueProcessor;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.MD5;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;
/**
 * 
 * @ClassName:StaffController
 * @Description:员工
 * @Author tdd
 * @Date 2018年4月25日下午5:05:43
 * @version 1.0
 */
@Controller
@RequestMapping("/staff")
public class StaffController extends BaseController{
	
	@Resource StaffService  staffService;
	@Resource RegService regService;
	@Resource DepartmentService departmentService;
	@Resource JobService jobService;
	
	/**
	 * 条件分页查询
	 * @param staff 员工实体类
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public String list(Staff staff,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		/*
		 * 条件分页查询内容
		 */
		List<Staff> list = staffService.findPageByMution(staff);
		/*
		 * 条件查询总条数
		 */
		Integer total = staffService.selectCountByMution(staff);  
		
		/*
		 * 转为json数据传至页面
		 */
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		//创建result
		JSONObject result = new JSONObject();
		//转json数据
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		//添加入result
		result.put("rows", jsonArray);
		result.put("total", total);
		//发送result
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 添加员工
	 * @param staff 员工实体类
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/add")
	public void add(@RequestParam("photo") CommonsMultipartFile photo,Staff staff,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
        
		// 添加文件返回保存路径
		String savePath = CreateFileReturnPath.createFile(photo, request);
		// 判断保存路径是否为空
		if (StringUtil.isNotEmpty(savePath)) {
			// 实体类set路径
			staff.setSreserve1(savePath);
		}
		
		
		//从session中取出用户身份信息
       Staff userSession = (Staff) session.getAttribute("staff");
       String staffname = userSession.getSname();
       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd");   
       String   date   =   sDateFormat.format(new Date());
       staff.setSentry(staffname);
       staff.setSentrytime(date);
		//MD5加密
		staff.setPass(MD5.md5Encode(staff.getPass()));
		/*
		 * 添加返回id
		 */
		Long staid = staffService.add(staff);
		if (null != staid) {
			response.getWriter().print("1");
		}else{
			response.getWriter().print("0");
		}
	}
	/**
	 * 根据id查员工
	 * @param staid 员工id
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryById")
	@ResponseBody
	public Staff queryById(Long staid,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		Staff staff = staffService.queryById(staid);
		return staff;
	}
	/**
	 * 根据条件查员工
	 * @param staff 员工实体类
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<Staff> queryAllByMution(Staff staff,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		List<Staff> list = staffService.queryAllByMution(staff);
		return list;
	}
	/**
	 * 修改员工
	 * @param staff 员工实体类
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/update")
	@ResponseBody
	public String update(@RequestParam("photo") CommonsMultipartFile photo,Staff staff,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		// 添加文件返回保存路径
		String savePath = CreateFileReturnPath.createFile(photo, request);
		// 判断保存路径是否为空
		if (StringUtil.isNotEmpty(savePath)) {
			// 实体类set路径
			staff.setSreserve1(savePath);
		}
		
		//从session中取出用户身份信息
       Staff userSession = (Staff) session.getAttribute("staff");
       String staffname = userSession.getSname();
       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd");   
       String   date   =   sDateFormat.format(new Date());
       staff.setSentry(staffname);
       staff.setSentrytime(date);
		//MD5加密
		if(null != staff.getPass() && !staff.getPass().equals("")){
			staff.setPass(MD5.md5Encode(staff.getPass()));
		}else{
			Staff queryById = staffService.queryById(staff.getStaid());
			staff.setPass(queryById.getPass());
		}
		/*
		 * 修改返回影响行数
		 */
		Integer count = staffService.update(staff);
		if (count >= 1) {
			return "1";
		}else{
			return "0";
		}
	}
	/**
	 * 多删除
	 * @param ids 员工id累加字符串
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		System.out.println(ids);
		ids=ids.replace("'",""); 
		/*
		 * 多删除返回影响行数
		 */
		Integer count = staffService.deleteIds(ids);
		if (count >= 1) {
			response.getWriter().print("1");
		}else{
			response.getWriter().print("0");
		}
	}
	
	
	/**
	 * 导出当前页数据
	 * @param staff 员工实体类
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExport")
	public void doExport(Staff staff,HttpServletResponse response) throws Exception {
		List<Staff> staffs = staffService.findPageByMution(staff);
		List<List<String>> lists = staffzhuanlist(staffs);
		ExcelUtils.export("员工当前数据",namess(), response,lists );
	}	
	/**
	 * 导出所有数据
	 * @param staff 员工实体类
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExportall")
	public void doExportall(Staff staff,HttpServletRequest request,HttpServletResponse response) throws Exception{
		//未删除
		List<Staff> staffs=staffService.queryAllByMution(staff);
		List<List<String>> lists = staffzhuanlist(staffs);
		ExcelUtils.export("员工所有数据",namess(), response,lists);
	}	
	
	
	/**
	 * 导入
	 * @param file 导入的excel文件
	 * @param request
	 * @param response
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException{
		   String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/"+file.getOriginalFilename());
		   File newFile=new File(savePath);
		   //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	       file.transferTo(newFile);
	       //取文件后缀
	       String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
	       System.out.println(subfix);
	       List<List<String>> lists = new ArrayList<>();
	       //获取导入行数
	       List<String> names = names();
	       int num = names.size();
	       if(subfix.equals("xls")){
	    	   lists = ExcelUtils.readXls(savePath, request,num);
	 	   }else if(subfix.equals("xlsx")){
	 		   lists = ExcelUtils.readXlsx(savePath, request,num);
	 	   }else{
	 	   		response.getWriter().print("0");
	 	   }
	       
	       HttpSession session  = request.getSession();
	        //从session中取出用户身份信息
	       Staff userSession = (Staff) session.getAttribute("staff");
	       String staffname = userSession.getSname();;
	       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd");   
	       String   date   =   sDateFormat.format(new Date());
	       
	       int flag = 1; 
	       for (int i = 0; i < lists.size(); i++) {
	    	   List<String> list = new ArrayList<>();
	    	   list= lists.get(i);
	    
	    	   Staff staff =new Staff();
	    	   staff.setScode(list.get(0));
	    	   staff.setSname(list.get(1));
	    	   
	    	   if(null != list.get(2) && !list.get(2).equals("")){
	    		   staff.setPass(MD5.md5Encode(list.get(2)));
	    	   }else{
	    		   staff.setPass(MD5.md5Encode("123"));
	    	   }
	    	   
	    	   if(null != list.get(3) && "" != list.get(3)) {
	    		   if(list.get(3).equals("女")){
		    		   staff.setSex("女");
		    	   }else{
		    		   staff.setSex("男");
		    	   }
	    	   }else {
	    		   staff.setSex("");
	    	   }
	    	   
	    	   SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  
				try {
					Date sbir = null;
					if(list.get(4) != null && list.get(4) != "") {
						sbir = sdf.parse(list.get(4).trim());
					}
					staff.setSbir(sbir);
				} catch (ParseException e) {
					flag = 0;
					break;
				}  
	    	   
	    	   //地区
	    	   /*Reg reg= new Reg();
	    	   reg.setRname(list.get(5));
	    	   List<Reg> regs = regService.queryAllByMution(reg);
	    	   if(regs.size()==1){
	    		   staff.setRid(regs.get(0).getRid());
	    	   }else{
	    		   flag = 0;
	    		   break;
	    	   }*/
	    	   
	    	   //部门
	    	   Department department = new Department();
	    	   if(list.get(5) != null) {
	    		   department.setDname(list.get(5));
	    		   List<Department> departments = departmentService.queryAllByMution(department);
		    	   if(departments.size()==1){
		    		   staff.setDid(departments.get(0).getDid());
		    	   }else{
		    		   flag = 0;
		    		   break;
		    	   }
	    	   }else {
	    		   department.setDname("");
	    	   }
	    	  
	    	   
	    	   //职务
	    	   Job job = new Job();
	    	   if(list.get(6) != null) {
	    		   job.setJname(list.get(6));
		    	   List<Job> jobs = jobService.queryAllByMution(job);
		    	   if(jobs.size()==1){
		    		   staff.setPid(jobs.get(0).getJid());
		    	   }else{
		    		   flag = 0;
		    		   break;
		    	   }
	    	   }else {
	    		   job.setJname("");
	    	   }
	    	  
	    	   staff.setSway(list.get(7));	
	    	   if(list.get(8) != null) {
		    	   if ("小学".endsWith(list.get(8))) {
		    		   staff.setSeducation("小学");
		    	   }else if("初中".endsWith(list.get(8))){
		    		   staff.setSeducation("初中");
		    	   }else if("高中".endsWith(list.get(8))){
		    		   staff.setSeducation("高中");
		    	   }else if("初中中专".endsWith(list.get(8))){
		    		   staff.setSeducation("初中中专");
		    	   }else if("高中中专".endsWith(list.get(8))){
		    		   staff.setSeducation("高中中专");
		    	   }else if("大专".endsWith(list.get(8))){
		    		   staff.setSeducation("大专");
		    	   }else if("本科".endsWith(list.get(8))){
		    		   staff.setSeducation("本科");
		    	   }else if("研究生".endsWith(list.get(8))){
		    		   staff.setSeducation("研究生");
				   }else{
					   staff.setSeducation("小学");
				   }
	    	   }else {
	    		   staff.setSeducation("");	
	    	   }
	    	   
	    	   
	    	   //staff.setSschool(list.get(9));
	    	   //staff.setSmajor(list.get(10));
	    	   
				/*try {
					Date isndate = null;
					isndate = sdf.parse(list.get(11).trim());
					staff.setIsndate(isndate);
				} catch (ParseException e) {
					flag = 0;
					break;
				}  */
	    	   
	    	   
	    	   
	    	   
	    	   //staff.setSqq(list.get(13));
	    	   //staff.setSmail(list.get(14));
	    	   //staff.setSaddress(list.get(15));
	    	   //staff.setSman(list.get(16));
	    	   //staff.setStele(list.get(17));
	    	   staff.setSreserve3(list.get(9));
	    	   staff.setSremark(list.get(10));
	    	
	    	   int ff = addstaff(staff, request, date, staffname);
	    	   staff = null;
	    	   if (ff == 0) {
	    		   flag = 0;
	    		   break;
	    	   }
	       }
	       response.getWriter().print(flag);
	 }
	/**
	 * 导出模板的表头
	 * @return
	 */
	public List<String> names(){
		List<String> list = new ArrayList<>();
		list.add("帐号");
		list.add("姓名");
		list.add("密码");
		list.add("性别");
		list.add("出生日期");
		//list.add("地区");
		list.add("部门");
		list.add("职务");
		list.add("电话");
		list.add("学历");
		//list.add("学校");
		//list.add("专业");
		//list.add("入社日期");
		//list.add("联系方式");
		//list.add("QQ");
		//list.add("邮箱");
		//list.add("家庭住址");
		//list.add("紧急联系人");
		list.add("角色");
		list.add("备注");
		return list;
	}
	/**
	 * 导出数据表头
	 * @return
	 */
	public List<String> namess(){
		List<String> list = new ArrayList<>();
		list.add("账号");
		list.add("姓名");
		list.add("性别");
		list.add("出生日期");
		//list.add("地区");
		list.add("部门");
		list.add("职务");
		//list.add("入社日期");
		list.add("电话");
		list.add("学历");
		//list.add("学校");
		//list.add("专业");
		//list.add("QQ");
		//list.add("邮箱");
		//list.add("家庭住址");
		//list.add("紧急联系人");
		//list.add("联系方式");
		list.add("角色");
		list.add("备注");
		list.add("创建人");
		list.add("创建时间");
		return list;
	}
	/**
	 * 根据导出数据表头把List<staff>转List<List<String>>
	 * @param staffs
	 * @return
	 */
	public List<List<String>> staffzhuanlist (List<Staff> staffs){
		List<List<String>> lists = new ArrayList<>();
		for (Staff staff : staffs) {
			List<String> list = new ArrayList<>();
			list.add(staff.getScode());
			list.add(staff.getSname());
			list.add(staff.getSex());
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
			if(null != staff.getSbir()){
				String str=sdf.format(staff.getSbir()); 
				list.add(str);
			}else{
				list.add("");
			}
			/*if(null != staff.getReg()){
				list.add(staff.getReg().getRname());
			}else{
				list.add("");
			}*/
			if(null != staff.getDepartment()){
				list.add(staff.getDepartment().getDname());
			}else{
				list.add("");
			}
			if(null != staff.getJob()){
				list.add(staff.getJob().getJname());
			}else{
				list.add("");
			}
			/*if (null != staff.getIsndate()) {
				String str=sdf.format(staff.getIsndate()); 
				list.add(str);
			}else{
				list.add("");
			}*/
			
			list.add(staff.getSway());
			list.add(staff.getSeducation());
			/*list.add(staff.getSschool());
			list.add(staff.getSmajor());
			list.add(staff.getSqq());
			list.add(staff.getSmail());
			list.add(staff.getSaddress());
			list.add(staff.getSman());
			list.add(staff.getStele());*/
			list.add(staff.getSreserve3());
			list.add(staff.getSremark());
			list.add(staff.getSentry());
			list.add(staff.getSentrytime());
			lists.add(list);
			list = null;
		}
		return lists;
	}
	/**
	 * 导入数据是的添加方法（如果不满足添加条件，直接过滤）
	 * @param staff
	 * @param request
	 * @param date
	 * @param staffname
	 * @return
	 */
	public int addstaff(Staff staff,
			HttpServletRequest request,String date,String staffname){
		int flag = 0;
    	//添加员工
    	//录入人
		staff.setSentry(staffname);
    	//录入时间
		staff.setSentrytime(date);
    	//添加
    	Long id = staffService.add(staff);
    	//添加成功
    	if (null != id && id >= 1) {
    		flag = 1;
    	} 
		return flag;
	}
	
	/**
	 * 跳转到对应页面
	 * @param url 需要跳转页面的路径（例如tdd/staff/staff）
	 * @return
	 */
	@RequestMapping("/staff_page")
	public String staff_page(String url) {
		
		return url;
	}
	
	/**
	 * 文件导入返回路径
	 * @param file  文件
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public String upload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 可以方便地修改日期格式
	    /*String nowtime = dateFormat.format(now);*/
	    //指定目录并判断目录是否存在
	    File fileMl = new File("E:\\image");
	    if (!fileMl.exists()) {
	    	fileMl.mkdirs();
	    }
	    //E:\\白板上传文件\\yyyyMMddHHmmss
	    String path = fileMl.getPath()+"\\"+dateFormat.format(now);
	    //判断是否添加图片
	    if (file.getSize() != 0) {
	    	//最后一个“.”后的数据（.TXT）
	    	int pos =file.getOriginalFilename().lastIndexOf(".");
	    	String fileext = file.getOriginalFilename().substring(pos); 
	    	//项目路径+时间.XXX
	    	/*String savePath = request.getServletContext().getRealPath("图片"+nowtime+fileext);*/
	    	String savePath=path+fileext;
	    	File newFile=new File(savePath);
	    	//通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	    	file.transferTo(newFile);
	    	//判断文件目录的存在
	    	return savePath;
		}else{
			return null;
		}
	    
	}
	
	
	/**
	 * 文件导出
	 * @param down 文件路径
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/upDownlodeFile")
	public void  down(String down,HttpServletRequest request, HttpServletResponse response) throws Exception{
		File outfile = new File(down);
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 可以方便地修改日期格式
	    String nowtime = dateFormat.format(now);
		if (outfile.exists()) {
			int pos =outfile.getName().lastIndexOf(".");
			String fileext = outfile.getName().substring(pos);
			String filename = nowtime+fileext;// 获取文件名称
			InputStream fis = new BufferedInputStream(new FileInputStream(
					down));
			byte[] buffer = new byte[fis.available()];  
			fis.read(buffer);  //读取文件流
			fis.close();
			response.reset();  //重置结果集
			response.addHeader("Content-Disposition", "attachment;filename="
					+ new String(filename.replaceAll(" ", "").getBytes("utf-8"),
							"iso8859-1"));  //返回头 文件名
			response.addHeader("Content-Length", "" + outfile.length());  //返回头 文件大小
			response.setContentType("application/octet-stream");    //设置数据种类
			//获取返回体输出权
			OutputStream os = new BufferedOutputStream(response.getOutputStream());  
			os.write(buffer); // 输出文件
			os.flush();
			os.close();
		}else {
		    //response.setContentType("text/html;charset=utf-8");    
		    //response.getWriter().write("<script>alert('该文件已删除');window.location.reload();</script>");
		    //response.getWriter().write("<script>alert('网页将跳转到test.do'); window.location='test.do' ;window.close();</script>");   
		    //response.getWriter().flush();  
		    
			//response.sendError(200, "File notff found!"); 
		}
	}
	
	
	/**
	 * 查询签名图片信息
	 * @param id 员工id
	 * @param response 响应
	 */
	@RequestMapping("/myPicture")
	public void myPicture(Long id,HttpServletResponse response,HttpServletRequest request) {

		Staff staff = staffService.queryById(id);
		String path = staff.getSreserve1();
		
		// 动态获取项目路径+相对路径
		String projectPath = request.getSession().getServletContext()
				.getRealPath("/")
				+ path;
		
		if(path != null) {
			try {
				path.replace("\\","\\\\");
				FileInputStream in = new FileInputStream(new File(projectPath.replace("\\",File.separator))); 
				OutputStream o = response.getOutputStream(); 
				 int l = 0; 
				 byte[] buffer = new byte[4096]; 
				while((l = in.read(buffer)) != -1){ 
				o.write(buffer,0,l); 
				} 
				o.flush(); 
				in.close(); 
				o.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
	}
	
}
